import { createRouter, createWebHistory } from "vue-router";
import { getUserMenu } from "@/api/routes";
import { useMeanStore } from "@/store/menus";
import { routerConponent } from "@/utils/routerMap";
const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/login",
    name: "Login",
    meta: {
      title: "登录",
      keepAlive: true,
      requireAuth: false,
    },
    component: () => import("@/views/login/index.vue"),
  },
  {
    path: "/404",
    name: "404",
    meta: {
      title: "404",
      keepAlive: true,
      requireAuth: false,
    },
    component: () => import("@/views/404.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

const filterRoutes = (data) => {
  let userRoute = [];
  data.forEach((menu) => {
    userRoute.push({
      name: menu.name,
      path: menu.path,
      meta: menu.meta,
      redirect: menu.redirect || "",
      component: routerConponent[menu.component],
      children: menu.children ? filterRoutes(menu.children) : [],
    });
  });
  // console.log("userRoute: ", userRoute);
  return userRoute;
};

// 需要过滤掉的路由
const filterRoute = ["/login", "/404", "/"];

router.beforeEach((to, from, next) => {
  // 判断路由指向是否在需要过滤的路由地址数组里
  // 如果在，则直接跳进页面，无需判断
  if (filterRoute.indexOf(to.path) !== -1) {
    next();
    return false;
  }

  let token = sessionStorage.getItem("token");
  const useMean = useMeanStore();
  // console.log("hasRoute", useMean.hasRoute);
  if (!token) {
    // console.log("还没有token！！！");
    next({ path: "/login" });
  } else if (!useMean.hasRoute) {
    let role = JSON.parse(sessionStorage.getItem("role"));
    getUserMenu(role).then((res) => {
      useMean.setMenuList(res.data.routes);
      const pageRoute = filterRoutes(res.data.routes);
      // console.log("pageRoute: ", pageRoute);
      pageRoute.forEach((menu) => {
        router.addRoute(menu);
      });
    });
    useMean.changeRouteStatus(true);
    next({ path: to.path });
  } else {
    const matchedRoute = router
      .getRoutes()
      .find((route) => route.path === to.path);
    if (!matchedRoute) {
      // 如果路径未匹配，重定向到 404 页面
      next({ path: "/404" });
    } else {
      next();
    }
  }
});

export default router;
